package com.beteng.su.betengsu.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.beteng.su.betengsu.R;
import com.beteng.su.betengsu.base.APPConstants;
import com.beteng.su.betengsu.base.BaseActivity;
import com.beteng.su.betengsu.bean.AreaBean;
import com.beteng.su.betengsu.bean.UserBean;
import com.beteng.su.betengsu.net.webservice.SiteService;
import com.beteng.su.betengsu.utils.CommonUtils;
import com.beteng.su.betengsu.utils.DateTimeUtils;
import com.beteng.su.betengsu.utils.StringUtil;
import com.blankj.utilcode.util.CacheUtils;
import com.blankj.utilcode.util.EmptyUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.SnackbarUtils;
import com.blankj.utilcode.util.StringUtils;

import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import czm.statebutton.StateButton;
import dmax.dialog.SpotsDialog;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import io.realm.Realm;

/**
 * Created by chenzhimin on 2017/9/5.
 */

public class LoginActivity extends BaseActivity {


    private static final String UPDATA_AREA_TIME_STAMP = "UPDATA_AREA_TIME_STAMP";

    //是否第一次启动
    private boolean isFirstBootApp;
    private static final String  DEFALUT_TIME = "2012/8/16";

    private boolean isLoginSuccess;


    @BindView(R.id.et_username)
    EditText mEtUsername;
    @BindView(R.id.et_password)
    EditText mEtPassword;
    @BindView(R.id.btn_login)
    StateButton mBtnLogin;
    @BindView(R.id.imageView)
    ImageView mImageView;

    public static void start(Context context) {
        Intent starter = new Intent(context, LoginActivity.class);
        context.startActivity(starter);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        mEtUsername.setText("003");
        mEtPassword.setText("003");
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_login;
    }


    @Override
    public void setListener() {
        mBtnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (StringUtils.isEmpty(mEtUsername.getText().toString())||StringUtils.isEmpty(mEtPassword.getText().toString())) {
                    SnackbarUtils.with(view).setMessage("用户名或密码不能为空").showWarning();
                    return;
                }

                getLoginInfo(mEtUsername.getText().toString(),mEtPassword.getText().toString());

            }
        });
    }


    public void getLoginInfo(String userName, String psw) {

        showLoading();


        HashMap<String,Object> params = new HashMap<>();
        params.put("UserNo",userName);
        params.put("Password",psw);
        params.put("MacAddress","");
        params.put("SN","");

        SiteService.getInstants().getLogin(params,this)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<UserBean>() {
                    @Override
                    public void accept(UserBean userBean) throws Exception {

                        hideLoading();

                        CacheUtils.getInstance().put(APPConstants.SP_USER, userBean);

                        getAreaDbInfo();

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideLoading();
                        SnackbarUtils.with(mBtnLogin).setMessage(throwable.getMessage()).showWarning();
                    }
                });




    }

    private void getAreaDbInfo(){

        final SpotsDialog spotsDialog = new SpotsDialog(this, "正在加载数据库信息\n请稍后...");
        spotsDialog.setCancelable(false);
        spotsDialog.show();
        String lastRefreshTime = SPUtils.getInstance().getString(UPDATA_AREA_TIME_STAMP,DEFALUT_TIME);

        HashMap<String,Object> params = new HashMap<>();
        params.put("lastRefreshTime",lastRefreshTime);
        SiteService.getInstants().getArea(params,this)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(final String areaBeens) throws Exception {

                        Realm.getDefaultInstance().executeTransaction(new Realm.Transaction() {
                            @Override
                            public void execute(@NonNull Realm realm) {
                                realm.createOrUpdateAllFromJson(AreaBean.class,areaBeens);
                                realm.commitTransaction();
                                SPUtils.getInstance().put(UPDATA_AREA_TIME_STAMP, DateTimeUtils.getDateWithFormat("yyyy/MM/dd"));
                                spotsDialog.dismiss();
                                MainActivity.start(LoginActivity.this);
                            }
                        } );


                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        LogUtils.e(throwable.getMessage());
                        SnackbarUtils.with(mBtnLogin).setMessage(throwable.getMessage()).showWarning();
                        spotsDialog.dismiss();
                    }
                });
    }


}
